<template>
    <div class="app-container">
        <div>
            <p class="dialogTitle title">当前地震事件:
                <span v-if="currentEvent">{{ currentEvent.eventName }}</span>
                <span v-else>请在地震事件管理中设置当前地震事件</span>
            </p>
        </div>

        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="100px" v-show="showSearch">
            <el-form-item label="结构类型" prop="structureType">
                <el-select v-model="queryParams.structureType" placeholder="请选择结构类型" clearable>
                    <el-option v-for="item in option" :key="item.structureType" :label="item.structureType"
                        :value="item.structureType">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="审核状态" prop="checkStatus">
                <el-select v-model="queryParams.checkStatus" placeholder="请选择审核状态" clearable>
                    <el-option
                        v-for="item in [{ label: '未审核', value: '1' }, { label: '审核通过', value: '2' }, { label: '审核不通过', value: '3' }]"
                        :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="破坏类型" prop="destructionType">
                <el-select v-model="queryParams.destructionType" placeholder="请选择破坏类型" clearable>
                    <el-option v-for="item in option1" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="抽样点名称" prop="samplingPointName">
                <el-input v-model="queryParams.samplingPointName" placeholder="请输入抽样点名称" clearable />
            </el-form-item>
            <el-form-item label="样本编号" prop="sampleCode">
                <el-input v-model="queryParams.sampleCode" placeholder="请输入样本编号" clearable />
            </el-form-item>
            <el-form-item label="调查员" prop="createUserName">
                <el-input v-model="queryParams.createUserName" placeholder="请输入调查员" clearable />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleQuery">搜索</el-button>
                <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" :disabled="!currentEvent || dataList.length == 0 || multiple"
                    @click="handleMoreAudie">批量审核</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" :disabled="!currentEvent || dataList.length == 0"
                    @click="handleDel">批量删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" :disabled="!currentEvent||dataList.length==0" @click="handleExport">导出</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="dataList" stripe  row-key="id" @selection-change="handleSelectionChange">
            <el-table-column type="selection" align="center" :reserve-selection="true" width="55" />
            <el-table-column label="序号" align="center" width="55">
                <template #default="scope">
                    <span>{{ (queryParams.page - 1) * queryParams.rows + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column label="房屋单体样本编号" align="center" prop="sampleCode">
                <template #default="scope">
                    <span style="color: #107ce1;cursor: pointer;" @click="handleEdit(scope.row)">{{
                            scope.row.sampleCode
                    }}</span>
                </template>
            </el-table-column>
            <el-table-column label="房屋单体名称" align="center" prop="name" />
            <el-table-column label="抽样点名称" align="center" prop="samplingPointName" />
            <el-table-column label="破坏类型" align="center" prop="destructionType">
                <template #default="scope">
                    <span v-if="scope.row.destructionType == '0'">基本完好</span>
                    <span v-if="scope.row.destructionType == '1'">轻微破坏</span>
                    <span v-if="scope.row.destructionType == '2'">中等破坏</span>
                    <span v-if="scope.row.destructionType == '3'">严重破坏</span>
                    <span v-if="scope.row.destructionType == '4'">损坏</span>
                </template>
            </el-table-column>
            <el-table-column label="用途类型" align="center" prop="purposeType">
                <template #default="scope">
                    <span v-if="scope.row.purposeType == '0'">农村住宅</span>
                    <span v-if="scope.row.purposeType == '1'">农村公用</span>
                    <span v-if="scope.row.purposeType == '2'">城市住宅</span>
                    <span v-if="scope.row.purposeType == '3'">城市公用</span>
                    <span v-if="scope.row.purposeType == '4'">政府办公</span>
                    <span v-if="scope.row.purposeType == '5'">教育系统</span>
                    <span v-if="scope.row.purposeType == '6'">卫生系统</span>
                </template>
            </el-table-column>
            <el-table-column label="结构类型" align="center" prop="structureType" />
            <el-table-column label="破坏情况" align="center" prop="destructionType">
                <template #default="{row}">
                    {{option1.find(item => item.value === row.destructionType)?.label}}
                </template>
            </el-table-column>
            <el-table-column label="建筑面积" align="center" prop="floorage" />
            <el-table-column label="审核状态" align="center" prop="checkStatus">
                <template #default="scope">
                    <span v-if="scope.row.checkStatus == '1'">未审核</span>
                    <span v-if="scope.row.checkStatus == '2'">审核通过</span>
                    <span v-if="scope.row.checkStatus == '3'">审核不通过</span>
                </template>
            </el-table-column>
            <el-table-column label="调查员" align="center" prop="createUserName" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button type="text" @click="handleAudit(scope.row)">审核</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
            @pagination="getList" />


        <el-dialog title="查看房屋单体样本数据" v-model="open" width="900px" append-to-body>
            <el-form ref="addRef" label-width="190px" :model="form" :rules="rules">
                <el-row style="margin: 20px 0;">
                    <el-col :span="24">
                        <el-form-item label="行政区划"  required>
                            <span>{{ form.province }}{{ form.city }}{{ form.area }}{{ form.address }}</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="抽样点名称" prop="samplingPointName">
                            <el-select v-model="form.samplingPointName" style="width: 100%;">
                                <el-option v-for="item in option4" :key="item.id" :label="item.samplingPointName"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="经度" prop="longitude" required>
                            <el-input v-model="form.longitude" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="纬度" prop="latitude" required>
                            <el-input v-model="form.latitude" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="房屋单体名称" prop="name">
                            <el-input v-model="form.name" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="结构类型" prop="structureType">
                            <el-select v-model="form.structureType" style="width: 100%;">
                                <el-option v-for="item in option" :key="item.structureType" :label="item.structureType"
                                    :value="item.structureType">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="破坏情况" prop="destructionType">
                            <el-select v-model="form.destructionType" style="width: 100%;">
                                <el-option v-for="item in option1" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="建筑面积(平方米、房间数)" prop="floorage">
                            <el-input v-model="form.floorage" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="用途类型" prop="purposeType">
                            <el-select v-model="form.purposeType" style="width: 100%;">
                                <el-option v-for="item in option2" :key="item.value" :label="item.label"
                                    :value="item.value" clearable>
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="是否为典型房屋" prop="isTypicalHouse">
                            <el-radio-group v-model="form.isTypicalHouse">
                                <el-radio label="是">是</el-radio>
                                <el-radio label="否">否</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="损失值(元)" prop="lossValue">
                            <el-input v-model="form.lossValue" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="室内外财产损失比例" prop="propertyLossProportion">
                            <el-input v-model="form.propertyLossProportion" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="是否为中高档装修">
                            <el-radio-group v-model="form.isMediumAndHigh">
                                <el-radio label="是">是</el-radio>
                                <el-radio label="否">否</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="具体描述情况">
                            <el-input v-model="form.specificDescription" type="textarea" maxlength="500"
                                show-word-limit :autosize="{ minRows: 5, maxRows: 5 }" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="照片">
                            <file-upload ref="uploadRef1" v-model="form.enclosurePhoto" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="视频">
                            <file-upload ref="uploadRef2" v-model="form.enclosureVideo" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="音频">
                            <file-upload ref="uploadRef3" v-model="form.enclosureAudio" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="相册">
                            <file-upload ref="uploadRef4" v-model="form.enclosureAlbum" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="handleUpdate">确 认</el-button>
                    <el-button @click="open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        
        <el-dialog title="审核管理" v-model="openAudit" width="600px" append-to-body>
            <el-form ref="auditRef" label-width="80px" :model="form1" :rules="rules">
                <el-row style="margin: 20px 0;">
                    <el-col>
                        <el-form-item label="审核结果" prop="checkStatus">
                            <el-select v-model="form1.checkStatus" style="width: 100%;">
                                <el-option v-for="item in [{ label: '通过', value: '2' }, { label: '不通过', value: '3' }]"
                                    :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="审核意见" prop="checkOpinion">
                            <el-input v-model="form1.checkOpinion" type="textarea" maxlength="500" show-word-limit
                                :autosize="{ minRows: 5, maxRows: 5 }" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="saveAudit">保 存</el-button>
                    <el-button @click="openAudit = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="housUnitSampleAudit">
import useEventStore from "@/store/modules/event";
import { getAllList, getDetail, getAllStructureTypeList, auditSave, getSamPoiList, updateAudit,deleteAudit } from "@/api/fieldWork/surveyAudit/housUnitSampleAudit.js"
const { proxy } = getCurrentInstance();
const dataList = ref([]);
const ids = ref();
const loading = ref(false);
const single = ref(true);
const multiple = ref(true);
const open = ref(false);
const total = ref(0);
const showSearch = ref(true);
const openAudit = ref(false);
const option = ref([]);
const option1 = ref([{ label: '基本完好', value: '0' }, { label: '轻微破坏', value: '1' }, { label: '中等破坏', value: '2' }, { label: '严重破坏', value: '3' }, { label: '毁坏', value: '4' }]);
const option2 = ref([{ label: '农村住宅', value: '0' }, { label: '农村公用', value: '1' }, { label: '城市住宅', value: '2' }, { label: '城市公用', value: '3' }, { label: '政府办公', value: '4' }, { label: '教育系统', value: '5' }, { label: '卫生系统', value: '6' }]);
const currentEvent = computed(() => useEventStore().currentEvent);
const option4 = ref([]);
const selectstatus = ref([]);
const isMorestatus = ref(false);
const validatePositiveNumver = (rule, value, callback) => {
    if (/(^[1-9]\d*$)/.test(value)) {
        callback()
    } else if (!value) {
        callback()
    } else {
        callback(new Error('请输入正整数'))
    }
};
const validatePositiveNumver1 = (rule, value, callback) => {
    if (/(^[1-9]\d*$)/.test(value)) {
        callback()
    } else if (!value) {
        callback(new Error('建筑面积不能为空'))
    } else {
        callback(new Error('请输入正整数'))
    }
};
const data = reactive({
    queryParams: {
        page: 1,
        rows: 10,
        structureType: undefined,
        checkStatus: undefined,
        destructionType: undefined,
        samplingPointName: undefined,
        sampleCode: undefined,
        createUserName: undefined,
    },
    form: {},
    form1:{},
    rules:{
        name: [{ required: true, trigger: "blur", message: "房屋单体名称不能为空" }],
        structureType: [{ required: true, trigger: "change", message: "结构类型不能为空" }],
        destructionType: [{ required: true, trigger: "change", message: "破坏情况不能为空" }],
        floorage: [{required: false, validator: validatePositiveNumver1, trigger: "blur" }],
        lossValue: [{ required: false, validator: validatePositiveNumver, trigger: "blur" }],
        propertyLossProportion: [{ required: false, validator: validatePositiveNumver, trigger: "blur" }],
        checkStatus: [{ required: true, trigger: "change", message: "审核结果不能为空" }],
        checkOpinion: [{ required: true, trigger: "blur", message: "审核意见不能为空" }],
    },
})
const { queryParams, form, form1, rules } = toRefs(data)

/** 多选框选中数据 */
function handleSelectionChange(selection) {
    single.value = selection.length != 1;
    multiple.value = !selection.length;
    ids.value = selection.map((item) => item.id);
    selectstatus.value = selection;
};
// 批量
function handleMoreAudie() {
    isMorestatus.value = true;
    openAudit.value = true;
    proxy.resetForm("auditRef");
    selectstatus.value = selectstatus.value;
    // form1.value.ids = ids.value.join(',');
}
// 批量删除
function handleDel(){
    let str=''
    let arr=[]
    if(selectstatus.value.length!==0){
        selectstatus.value.forEach((v,i)=>{
            arr.push(v.id)
        })
    }
    str=arr.toString('')
    proxy.$modal
      .confirm("请确认是否要删除选中该抽样点？",)
      .then(function () {
        return deleteAudit(str);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      })
      .catch(() => { });
}


// 审核
function handleAudit(row) {
    isMorestatus.value = false;
    openAudit.value = true;
    proxy.resetForm("auditRef");
    // form1.value.ids = row.id;
    selectstatus.value = row;
}

function saveAudit() {
    proxy.$refs["auditRef"].validate(valid => {
        if (valid) {
            if(isMorestatus.value){
                selectstatus.value.forEach(item=>{
                    item.checkStatus = form1.value.checkStatus;
                    item.checkOpinion = form1.value.checkOpinion;
                    item.xsemId = currentEvent.value.id
                });
            }else{
                selectstatus.value = [{...selectstatus.value,checkStatus:form1.value.checkStatus,checkOpinion:form1.value.checkOpinion,xsemId: currentEvent.value.id}];
            }
            auditSave({ list:selectstatus.value }).then(res => {
                proxy.$modal.msgSuccess("审核完成");
                openAudit.value = false;
                getList();
            })
        }
    })
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.page = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    dataList.value = [];
    proxy.resetForm("queryRef");
    handleQuery();
}

/** 导出按钮操作 */
function handleExport() {
    proxy.downloadTemplate('/houMonData/exportExcel', { xsemId: currentEvent.value.id ,...queryParams.value}, `房屋单体样本数据.xls`)
}

// 编辑
function handleEdit(row) {
    detail(row.id);
}

//处理附件格式
function eachFiles(fileName) {
    let deepFile = JSON.parse(JSON.stringify(proxy.$refs[fileName].fileList))
    let Ids = []
    for (var i = 0; i < deepFile.length; i++) {
        Ids.push(deepFile[i].attachId)
    }
    return Ids.join(",");
}

function handleUpdate() {
    form.value.enclosurePhoto = eachFiles('uploadRef1');
    form.value.enclosureVideo = eachFiles('uploadRef2');
    form.value.enclosureAudio = eachFiles('uploadRef3');
    form.value.enclosureAlbum = eachFiles('uploadRef4');
    proxy.$refs["addRef"].validate(valid => {
        if (valid) {
            updateAudit({ ...form.value, xsemId: currentEvent.value.id }).then(res => {
                proxy.$modal.msgSuccess("修改成功");
                open.value = false;
                getList();
            })
        }
    });
}


// 查看
function detail(id) {
    getDetail({ id: id }).then(res => {
        open.value = true;
        proxy.resetForm("addRef");
        form.value = res.data;
    })
}

/** 查询数据列表 */
function getList() {
    if (currentEvent.value) {
        loading.value = true;
        getAllList({ ...queryParams.value, xsemId: currentEvent.value.id }).then(response => {
            dataList.value = response.data.rows ? response.data.rows : [];
            total.value = response.data.total;
            loading.value = false;
        });
    } else {
        dataList.value = [];
        total.value = 0;
    }
}

function findAll() {
    getAllStructureTypeList().then(res => {
        option.value = res.data
    })
}

/** 查询所有抽样点名称 */
function getAllSamPoiList() {
    if (currentEvent.value) {
        getSamPoiList({ xsemId: currentEvent.value.id }).then(response => {
            option4.value = response.data;
        });
    } else {
        option4.value = [];
    }
}

onMounted(() => {
    setTimeout(() => {
        getList();
        getAllSamPoiList();
    }, 200)
})
findAll();
</script>

<style scoped lang="scss">
.title {
    margin: 0 0 20px !important;
}
</style>

